#!python3
import requests
import redis
from time import sleep
SET_NAME = "IP_SET"


def get_pool():
    res = [
        requests.get(
            'http://api.ip.data5u.com/dynamic/get.html?order=675048ae1aa4c54bdbcf9ba3e69029ec&sep=3'
        ).text.strip() for i in range(9)
    ]
    return ["http://" + i + "/" for i in res]


class IpPool(object):
    def __init__(self):
        self.con = redis.Redis(host='127.0.0.1',
                               port=6379,
                               decode_responses=True)

    def get_ip(self):
        ret = self.con.srandmember(SET_NAME)
        if not ret:
            return self.get_ip()
        return ret

    def maintain(self):
        while True:
            pool = get_pool()
            self.con.delete(SET_NAME)
            self.con.sadd(SET_NAME, *pool)
            sleep(2)


if __name__ == "__main__":
    IpPool().maintain()